//File Header
//////////////////////////////////////////////////////////////////////////////
//
//                     Copyright Yuriy Silvestrov 2007
//
////////////////////////////////////////////////////////////////////////////////
//
// This class file "Program.cs"
// part of XSD Configuration Section Generator
// Started by "yuriy@silvestrov.com" on 3/1/2007
// Last edit by "$Author$" on $Date$
//
////////////////////////////////////////////////////////////////////////////////
//
// Change log ()
//
//
//
////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using XsdConfigSection;

namespace xsd2cs
{
	class Program
	{
		static void Main(string[] args)
		{
			Xsd2CsOptions options = new Xsd2CsOptions();
			options.ProcessArgs(args);

			string xsdFileName = options.InputFile;
			string csFileName = options.outputFile;

			if (xsdFileName == null)
			{
				Console.WriteLine("Error: No input file set.");
				return;
			}
			else if (xsdFileName.EndsWith("xsd.cs"))
			{
				xsdFileName = xsdFileName.Remove(xsdFileName.Length - 3);
			}
			else if (!xsdFileName.EndsWith("xsd"))
			{
				Console.WriteLine("Error: Input file is not XML Schema Definition.");
				return;
			}
			FileInfo fi = new FileInfo(xsdFileName);

			if (!fi.Exists)
			{
				Console.WriteLine("Error: Can not open input file \"{0}\".", fi.FullName);
				return;
			}

			if (csFileName == String.Empty || csFileName == null)
			{
				csFileName = fi.DirectoryName + @"\" + fi.Name + ".cs";
			}

			XmlSchema schema = XmlSchema.Read(XmlReader.Create(xsdFileName), delegate(
				Object sender,
				ValidationEventArgs e
				)

			                                                                 	{ Console.WriteLine(e.Message); });


			using (Stream codeFile = File.Open(csFileName, FileMode.Create))
			{
				using (TextWriter sw = new StreamWriter(codeFile))
				{
					Xsd2CsTraversor xsd2cs = new Xsd2CsTraversor(schema);
					xsd2cs.CodeNamespaceName = options.@namespace;
					xsd2cs.IsCreatePartialClasses = options.usePartial;
					xsd2cs.XmlNamespaceName = options.xmlNamespace;

					xsd2cs.GenerateCode(sw);

					sw.Close();
				}
				codeFile.Close();
			}
		}
	}
}